'use client';

import React, {useState} from 'react';
import {motion, AnimatePresence} from 'framer-motion';
import {
    CogIcon,
    PlusIcon,
    PencilIcon,
    TrashIcon,
    ExclamationTriangleIcon,
    CheckIcon,
    XMarkIcon
} from '@heroicons/react/24/outline';
import {useAppStore} from '@/store';
import Card, {CardContent, CardHeader, CardTitle} from '@/components/ui/Card';
import type {ActivityType, MoodConfig} from '@/types';
import {cn} from '@/utils';

const Settings: React.FC = () => {
    const {
        settings,
        addActivityType,
        updateActivityType,
        deleteActivityType,
        addMoodConfig,
        updateMoodConfig,
        deleteMoodConfig,
        updateTotalCoins
    } = useAppStore();

    // 状态管理
    const [activeTab, setActiveTab] = useState<'activities' | 'moods' | 'general'>('activities');
    const [editingActivity, setEditingActivity] = useState<string | null>(null);
    const [editingMood, setEditingMood] = useState<string | null>(null);
    const [showAddActivity, setShowAddActivity] = useState(false);
    const [showAddMood, setShowAddMood] = useState(false);

    // 新增活动表单
    const [newActivity, setNewActivity] = useState({
        name: '',
        coinValue: 0,
        color: '#10B981',
        icon: '📝'
    });

    // 新增情绪表单
    const [newMood, setNewMood] = useState({
        name: '',
        emoji: '😊',
        coinModifier: 0,
        color: '#10B981'
    });

    // 编辑活动表单
    const [editActivityForm, setEditActivityForm] = useState({
        name: '',
        coinValue: 0,
        color: '',
        icon: ''
    });

    // 编辑情绪表单
    const [editMoodForm, setEditMoodForm] = useState({
        name: '',
        emoji: '',
        coinModifier: 0,
        color: ''
    });

    const handleAddActivity = () => {
        if (!newActivity.name.trim()) return;

        addActivityType({
            name: newActivity.name,
            coinValue: newActivity.coinValue,
            color: newActivity.color,
            icon: newActivity.icon,
            isCustom: true
        });

        setNewActivity({name: '', coinValue: 0, color: '#10B981', icon: '📝'});
        setShowAddActivity(false);
    };

    const handleAddMood = () => {
        if (!newMood.name.trim()) return;

        addMoodConfig({
            name: newMood.name,
            emoji: newMood.emoji,
            coinModifier: newMood.coinModifier,
            color: newMood.color
        });

        setNewMood({name: '', emoji: '😊', coinModifier: 0, color: '#10B981'});
        setShowAddMood(false);
    };

    const startEditActivity = (activity: ActivityType) => {
        setEditingActivity(activity.id);
        setEditActivityForm({
            name: activity.name,
            coinValue: activity.coinValue,
            color: activity.color || '#10B981',
            icon: activity.icon || '📝'
        });
    };

    const startEditMood = (mood: MoodConfig) => {
        setEditingMood(mood.id);
        setEditMoodForm({
            name: mood.name,
            emoji: mood.emoji,
            coinModifier: mood.coinModifier,
            color: mood.color
        });
    };

    const handleSaveActivity = () => {
        if (!editingActivity) return;

        updateActivityType(editingActivity, {
            name: editActivityForm.name,
            coinValue: editActivityForm.coinValue,
            color: editActivityForm.color,
            icon: editActivityForm.icon
        });

        setEditingActivity(null);
    };

    const handleSaveMood = () => {
        if (!editingMood) return;

        updateMoodConfig(editingMood, {
            name: editMoodForm.name,
            emoji: editMoodForm.emoji,
            coinModifier: editMoodForm.coinModifier,
            color: editMoodForm.color
        });

        setEditingMood(null);
    };

    const handleDeleteActivity = (id: string) => {
        if (window.confirm('确定要删除这个活动类型吗？这将影响所有相关的记录。')) {
            deleteActivityType(id);
        }
    };

    const handleDeleteMood = (id: string) => {
        if (window.confirm('确定要删除这个情绪配置吗？这将影响所有相关的记录。')) {
            deleteMoodConfig(id);
        }
    };

    const tabs = [
        {id: 'activities', label: '活动类型', icon: CogIcon},
        {id: 'moods', label: '情绪配置', icon: CogIcon},
        {id: 'general', label: '通用设置', icon: CogIcon}
    ] as const;

    return (
        <div className="space-y-6">
            <div>
                <h1 className="text-2xl font-bold text-gray-900">系统设置</h1>
                <p className="text-gray-600 mt-1">管理活动类型、情绪配置和系统参数</p>
            </div>

            {/* 选项卡 */}
            <div className="border-b border-gray-200">
                <nav className="-mb-px flex space-x-8">
                    {tabs.map((tab) => (
                        <button
                            key={tab.id}
                            onClick={() => setActiveTab(tab.id)}
                            className={cn(
                                'py-2 px-1 border-b-2 font-medium text-sm whitespace-nowrap',
                                activeTab === tab.id
                                    ? 'border-blue-500 text-blue-600'
                                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                            )}
                        >
                            {tab.label}
                        </button>
                    ))}
                </nav>
            </div>

            {/* 活动类型设置 */}
            {activeTab === 'activities' && (
                <motion.div
                    initial={{opacity: 0, y: 20}}
                    animate={{opacity: 1, y: 0}}
                    className="space-y-4"
                >
                    <div className="flex justify-between items-center">
                        <h2 className="text-lg font-semibold text-gray-900">活动类型管理</h2>
                        <motion.button
                            whileHover={{scale: 1.02}}
                            whileTap={{scale: 0.98}}
                            onClick={() => setShowAddActivity(true)}
                            className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                        >
                            <PlusIcon className="w-4 h-4"/>
                            添加活动类型
                        </motion.button>
                    </div>

                    {/* 添加活动表单 */}
                    <AnimatePresence>
                        {showAddActivity && (
                            <motion.div
                                initial={{opacity: 0, height: 0}}
                                animate={{opacity: 1, height: 'auto'}}
                                exit={{opacity: 0, height: 0}}
                            >
                                <Card className="p-4 border-2 border-blue-200 bg-blue-50">
                                    <h3 className="font-medium text-blue-900 mb-4">添加新活动类型</h3>
                                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                        <input
                                            type="text"
                                            placeholder="活动名称"
                                            value={newActivity.name}
                                            onChange={(e) => setNewActivity(prev => ({...prev, name: e.target.value}))}
                                            className="px-3 py-2 border border-gray-300 rounded-lg"
                                        />
                                        <input
                                            type="number"
                                            placeholder="金币值"
                                            value={newActivity.coinValue}
                                            onChange={(e) => setNewActivity(prev => ({
                                                ...prev,
                                                coinValue: parseInt(e.target.value) || 0
                                            }))}
                                            className="px-3 py-2 border border-gray-300 rounded-lg"
                                        />
                                        <input
                                            type="text"
                                            placeholder="图标"
                                            value={newActivity.icon}
                                            onChange={(e) => setNewActivity(prev => ({...prev, icon: e.target.value}))}
                                            className="px-3 py-2 border border-gray-300 rounded-lg text-center"
                                        />
                                        <input
                                            type="color"
                                            value={newActivity.color}
                                            onChange={(e) => setNewActivity(prev => ({...prev, color: e.target.value}))}
                                            className="h-10 w-full border border-gray-300 rounded-lg"
                                        />
                                    </div>
                                    <div className="flex gap-2 justify-end mt-4">
                                        <button
                                            onClick={() => setShowAddActivity(false)}
                                            className="px-4 py-2 text-gray-600 hover:text-gray-700"
                                        >
                                            取消
                                        </button>
                                        <button
                                            onClick={handleAddActivity}
                                            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                                        >
                                            添加
                                        </button>
                                    </div>
                                </Card>
                            </motion.div>
                        )}
                    </AnimatePresence>

                    {/* 活动列表 */}
                    <div className="grid gap-4">
                        {settings.activityTypes.map((activity, index) => (
                            <motion.div
                                key={activity.id}
                                initial={{opacity: 0, x: -20}}
                                animate={{opacity: 1, x: 0}}
                                transition={{delay: index * 0.05}}
                            >
                                <Card className="p-4">
                                    {editingActivity === activity.id ? (
                                        // 编辑模式
                                        <div className="space-y-4">
                                            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                                <input
                                                    type="text"
                                                    value={editActivityForm.name}
                                                    onChange={(e) => setEditActivityForm(prev => ({
                                                        ...prev,
                                                        name: e.target.value
                                                    }))}
                                                    className="px-3 py-2 border border-gray-300 rounded-lg"
                                                />
                                                <input
                                                    type="number"
                                                    value={editActivityForm.coinValue}
                                                    onChange={(e) => setEditActivityForm(prev => ({
                                                        ...prev,
                                                        coinValue: parseInt(e.target.value) || 0
                                                    }))}
                                                    className="px-3 py-2 border border-gray-300 rounded-lg"
                                                />
                                                <input
                                                    type="text"
                                                    value={editActivityForm.icon}
                                                    onChange={(e) => setEditActivityForm(prev => ({
                                                        ...prev,
                                                        icon: e.target.value
                                                    }))}
                                                    className="px-3 py-2 border border-gray-300 rounded-lg text-center"
                                                />
                                                <input
                                                    type="color"
                                                    value={editActivityForm.color}
                                                    onChange={(e) => setEditActivityForm(prev => ({
                                                        ...prev,
                                                        color: e.target.value
                                                    }))}
                                                    className="h-10 w-full border border-gray-300 rounded-lg"
                                                />
                                            </div>
                                            <div className="flex gap-2 justify-end">
                                                <button
                                                    onClick={() => setEditingActivity(null)}
                                                    className="p-1 text-gray-400 hover:text-gray-600"
                                                >
                                                    <XMarkIcon className="w-4 h-4"/>
                                                </button>
                                                <button
                                                    onClick={handleSaveActivity}
                                                    className="p-1 text-green-600 hover:text-green-700"
                                                >
                                                    <CheckIcon className="w-4 h-4"/>
                                                </button>
                                            </div>
                                        </div>
                                    ) : (
                                        // 显示模式
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center gap-4">
                                                <span className="text-2xl">{activity.icon}</span>
                                                <div>
                                                    <h3 className="font-semibold text-gray-900">{activity.name}</h3>
                                                    <div className="flex items-center gap-4 text-sm text-gray-600">
                            <span className={cn(
                                'font-medium',
                                activity.coinValue > 0 ? 'text-green-600' : activity.coinValue < 0 ? 'text-red-600' : 'text-gray-600'
                            )}>
                              {activity.coinValue > 0 ? '+' : ''}{activity.coinValue} 金币
                            </span>
                                                        <div
                                                            className="w-4 h-4 rounded-full border border-gray-300"
                                                            style={{backgroundColor: activity.color}}
                                                        />
                                                        {activity.isCustom && (
                                                            <span
                                                                className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
                                自定义
                              </span>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="flex gap-1">
                                                <motion.button
                                                    whileHover={{scale: 1.1}}
                                                    whileTap={{scale: 0.9}}
                                                    onClick={() => startEditActivity(activity)}
                                                    className="p-1 text-gray-400 hover:text-blue-600"
                                                >
                                                    <PencilIcon className="w-4 h-4"/>
                                                </motion.button>
                                                {activity.isCustom && (
                                                    <motion.button
                                                        whileHover={{scale: 1.1}}
                                                        whileTap={{scale: 0.9}}
                                                        onClick={() => handleDeleteActivity(activity.id)}
                                                        className="p-1 text-gray-400 hover:text-red-600"
                                                    >
                                                        <TrashIcon className="w-4 h-4"/>
                                                    </motion.button>
                                                )}
                                            </div>
                                        </div>
                                    )}
                                </Card>
                            </motion.div>
                        ))}
                    </div>
                </motion.div>
            )}

            {/* 情绪配置设置 */}
            {activeTab === 'moods' && (
                <motion.div
                    initial={{opacity: 0, y: 20}}
                    animate={{opacity: 1, y: 0}}
                    className="space-y-4"
                >
                    <div className="flex justify-between items-center">
                        <h2 className="text-lg font-semibold text-gray-900">情绪配置管理</h2>
                        <motion.button
                            whileHover={{scale: 1.02}}
                            whileTap={{scale: 0.98}}
                            onClick={() => setShowAddMood(true)}
                            className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                        >
                            <PlusIcon className="w-4 h-4"/>
                            添加情绪配置
                        </motion.button>
                    </div>

                    {/* 添加情绪表单 */}
                    <AnimatePresence>
                        {showAddMood && (
                            <motion.div
                                initial={{opacity: 0, height: 0}}
                                animate={{opacity: 1, height: 'auto'}}
                                exit={{opacity: 0, height: 0}}
                            >
                                <Card className="p-4 border-2 border-blue-200 bg-blue-50">
                                    <h3 className="font-medium text-blue-900 mb-4">添加新情绪配置</h3>
                                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                        <input
                                            type="text"
                                            placeholder="情绪名称"
                                            value={newMood.name}
                                            onChange={(e) => setNewMood(prev => ({...prev, name: e.target.value}))}
                                            className="px-3 py-2 border border-gray-300 rounded-lg"
                                        />
                                        <input
                                            type="number"
                                            placeholder="金币修正值"
                                            value={newMood.coinModifier}
                                            onChange={(e) => setNewMood(prev => ({
                                                ...prev,
                                                coinModifier: parseInt(e.target.value) || 0
                                            }))}
                                            className="px-3 py-2 border border-gray-300 rounded-lg"
                                        />
                                        <input
                                            type="text"
                                            placeholder="表情符号"
                                            value={newMood.emoji}
                                            onChange={(e) => setNewMood(prev => ({...prev, emoji: e.target.value}))}
                                            className="px-3 py-2 border border-gray-300 rounded-lg text-center"
                                        />
                                        <input
                                            type="color"
                                            value={newMood.color}
                                            onChange={(e) => setNewMood(prev => ({...prev, color: e.target.value}))}
                                            className="h-10 w-full border border-gray-300 rounded-lg"
                                        />
                                    </div>
                                    <div className="flex gap-2 justify-end mt-4">
                                        <button
                                            onClick={() => setShowAddMood(false)}
                                            className="px-4 py-2 text-gray-600 hover:text-gray-700"
                                        >
                                            取消
                                        </button>
                                        <button
                                            onClick={handleAddMood}
                                            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                                        >
                                            添加
                                        </button>
                                    </div>
                                </Card>
                            </motion.div>
                        )}
                    </AnimatePresence>

                    {/* 情绪列表 */}
                    <div className="grid gap-4">
                        {settings.moodConfigs.map((mood, index) => (
                            <motion.div
                                key={mood.id}
                                initial={{opacity: 0, x: -20}}
                                animate={{opacity: 1, x: 0}}
                                transition={{delay: index * 0.05}}
                            >
                                <Card className="p-4">
                                    {editingMood === mood.id ? (
                                        // 编辑模式
                                        <div className="space-y-4">
                                            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                                <input
                                                    type="text"
                                                    value={editMoodForm.name}
                                                    onChange={(e) => setEditMoodForm(prev => ({
                                                        ...prev,
                                                        name: e.target.value
                                                    }))}
                                                    className="px-3 py-2 border border-gray-300 rounded-lg"
                                                />
                                                <input
                                                    type="number"
                                                    value={editMoodForm.coinModifier}
                                                    onChange={(e) => setEditMoodForm(prev => ({
                                                        ...prev,
                                                        coinModifier: parseInt(e.target.value) || 0
                                                    }))}
                                                    className="px-3 py-2 border border-gray-300 rounded-lg"
                                                />
                                                <input
                                                    type="text"
                                                    value={editMoodForm.emoji}
                                                    onChange={(e) => setEditMoodForm(prev => ({
                                                        ...prev,
                                                        emoji: e.target.value
                                                    }))}
                                                    className="px-3 py-2 border border-gray-300 rounded-lg text-center"
                                                />
                                                <input
                                                    type="color"
                                                    value={editMoodForm.color}
                                                    onChange={(e) => setEditMoodForm(prev => ({
                                                        ...prev,
                                                        color: e.target.value
                                                    }))}
                                                    className="h-10 w-full border border-gray-300 rounded-lg"
                                                />
                                            </div>
                                            <div className="flex gap-2 justify-end">
                                                <button
                                                    onClick={() => setEditingMood(null)}
                                                    className="p-1 text-gray-400 hover:text-gray-600"
                                                >
                                                    <XMarkIcon className="w-4 h-4"/>
                                                </button>
                                                <button
                                                    onClick={handleSaveMood}
                                                    className="p-1 text-green-600 hover:text-green-700"
                                                >
                                                    <CheckIcon className="w-4 h-4"/>
                                                </button>
                                            </div>
                                        </div>
                                    ) : (
                                        // 显示模式
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center gap-4">
                                                <span className="text-2xl">{mood.emoji}</span>
                                                <div>
                                                    <h3 className="font-semibold text-gray-900">{mood.name}</h3>
                                                    <div className="flex items-center gap-4 text-sm text-gray-600">
                            <span className={cn(
                                'font-medium',
                                mood.coinModifier > 0 ? 'text-green-600' : mood.coinModifier < 0 ? 'text-red-600' : 'text-gray-600'
                            )}>
                              {mood.coinModifier > 0 ? '+' : ''}{mood.coinModifier} 金币修正
                            </span>
                                                        <div
                                                            className="w-4 h-4 rounded-full border border-gray-300"
                                                            style={{backgroundColor: mood.color}}
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="flex gap-1">
                                                <motion.button
                                                    whileHover={{scale: 1.1}}
                                                    whileTap={{scale: 0.9}}
                                                    onClick={() => startEditMood(mood)}
                                                    className="p-1 text-gray-400 hover:text-blue-600"
                                                >
                                                    <PencilIcon className="w-4 h-4"/>
                                                </motion.button>
                                                <motion.button
                                                    whileHover={{scale: 1.1}}
                                                    whileTap={{scale: 0.9}}
                                                    onClick={() => handleDeleteMood(mood.id)}
                                                    className="p-1 text-gray-400 hover:text-red-600"
                                                >
                                                    <TrashIcon className="w-4 h-4"/>
                                                </motion.button>
                                            </div>
                                        </div>
                                    )}
                                </Card>
                            </motion.div>
                        ))}
                    </div>
                </motion.div>
            )}

            {/* 通用设置 */}
            {activeTab === 'general' && (
                <motion.div
                    initial={{opacity: 0, y: 20}}
                    animate={{opacity: 1, y: 0}}
                    className="space-y-6"
                >
                    <h2 className="text-lg font-semibold text-gray-900">通用设置</h2>

                    {/* 系统信息 */}
                    <Card className="p-6">
                        <h3 className="font-medium text-gray-900 mb-4">系统信息</h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <span className="text-sm text-gray-600">活动类型数量</span>
                                <span className="font-semibold text-gray-900">{settings.activityTypes.length}</span>
                            </div>
                            <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <span className="text-sm text-gray-600">情绪配置数量</span>
                                <span className="font-semibold text-gray-900">{settings.moodConfigs.length}</span>
                            </div>
                        </div>
                    </Card>

                    {/* 使用说明 */}
                    <Card className="p-6">
                        <h3 className="font-medium text-gray-900 mb-4">使用说明</h3>
                        <div className="space-y-4 text-sm text-gray-600">
                            <div className="flex items-start gap-3">
                                <span
                                    className="flex-shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center font-semibold text-xs">1</span>
                                <p>在<strong>活动类型管理</strong>中设置各种活动的金币奖励或扣除。正值表示奖励，负值表示扣除。
                                </p>
                            </div>
                            <div className="flex items-start gap-3">
                                <span
                                    className="flex-shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center font-semibold text-xs">2</span>
                                <p>在<strong>情绪配置管理</strong>中设置不同情绪的金币修正值。这会影响记录活动时的最终金币计算。
                                </p>
                            </div>
                            <div className="flex items-start gap-3">
                                <span
                                    className="flex-shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center font-semibold text-xs">3</span>
                                <p>颜色和图标用于在界面中更好地区分不同的活动类型和情绪状态。</p>
                            </div>
                            <div className="flex items-start gap-3">
                                <span
                                    className="flex-shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center font-semibold text-xs">4</span>
                                <p>删除配置项时请谨慎，这可能会影响已有的活动记录。</p>
                            </div>
                        </div>
                    </Card>

                    {/* 数据管理 */}
                    <Card className="p-6">
                        <h3 className="font-medium text-gray-900 mb-4">数据管理</h3>
                        <div className="space-y-4">
                            <div className="p-4 border border-yellow-200 bg-yellow-50 rounded-lg">
                                <div className="flex items-center gap-2 text-yellow-800 mb-2">
                                    <ExclamationTriangleIcon className="w-5 h-5"/>
                                    <span className="font-medium">注意</span>
                                </div>
                                <p className="text-sm text-yellow-700">
                                    所有数据都保存在浏览器本地存储中。清除浏览器数据将导致所有记录丢失。
                                    建议定期导出重要数据进行备份。
                                </p>
                            </div>

                            <div className="flex gap-4">
                                <motion.button
                                    whileHover={{scale: 1.02}}
                                    whileTap={{scale: 0.98}}
                                    className="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                                    onClick={() => alert('导出功能开发中...')}
                                >
                                    导出数据
                                </motion.button>
                                <motion.button
                                    whileHover={{scale: 1.02}}
                                    whileTap={{scale: 0.98}}
                                    className="flex-1 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
                                    onClick={() => alert('导入功能开发中...')}
                                >
                                    导入数据
                                </motion.button>
                            </div>
                        </div>
                    </Card>
                </motion.div>
            )}
        </div>
    );
};

export default Settings;
